import ScrollBarLayout from '@/components/ScrollBarLayout';
import Cls from 'classnames';
import { useCallback, useContext, useEffect, useState } from 'react';
import { ChangeControllerContext } from '../common/useOAContext';
import { Checkbox, Form, Spin, Tooltip, TreeSelect, message } from 'antd';
import { useDescriptions, Descriptions } from '@/components/Descriptions';
import { downloadTemplate, getFileNameNotType, getLevelZeroJson, getLoadMapList, getSelectDataMapList, getTenantID, splitFileUrl } from '@/utils';
import { ILoadMapTypeAll } from '@/common';
import MyIcon from '@/components/MyIcon';
import { connect } from 'umi';
import moment from 'moment';
import { detailDiffServices, DetailedServices, editDetailServices } from '../services/UpdataService';
import { DescriptionsType, useDescriptionsType } from '@/components/DescriptionsType';
import DifferTable from '../mview/DifferTable';
import { TypographyTitle } from '@/components/Typography/TypographyTitle';

function addDisabledToTreeData(originalTreeData) {
  const newTreeData = originalTreeData?.map((node) => {
    const newNode = { ...node, disabled: true }; // 复制节点并添加disabled属性

    if (node.children) {
      newNode.children = addDisabledToTreeData(node.children); // 递归处理子节点
    }

    return newNode;
  });

  return newTreeData;
}

const DetailInfoCenterViewMainOA = ({ curRes }) => {
  /** 引入上下文 */
  const { styleFixCls, infoObj, taskId }: any = useContext(ChangeControllerContext);

  /**  获取数据字典 */
  const { loadMapInfo, mapLoading } = getLoadMapList([
    `${getTenantID()}${ILoadMapTypeAll.ASSET_TYPE}`, //资产类型
    `${getTenantID()}${ILoadMapTypeAll.AVERAGE_LIFE_METHOD}`, //折旧方式
    `${getTenantID()}${ILoadMapTypeAll.ASSET_SOURCE_TYPE}`, //资产来源
    `${getTenantID()}${ILoadMapTypeAll.ASSET_AREA}`, //资产存放地点
    `${getTenantID()}${ILoadMapTypeAll.MATERIAL_MIDI}`, //量化单位
  ]);

  const { DetailPushRun, Detaildata, getDetailReload, taskPushPagination, taskPushLoading } = DetailedServices(curRes);


  /** 修改资产回调 */
  const editDetailCallback = (res: any) => {
    if (infoObj?.inventoryID) {
      const obj: any = {
        inventoryID: infoObj?.inventoryID,
        page: 1,
        rows: 10,
        changeState: '0,2,3',
        // isInventory: 0,
      };
      DetailPushRun(obj);
    }
  };

  /** 修改资产接口 */
  const { editDetailRun, editDetailLoading } = editDetailServices(editDetailCallback);

  /** 资产类型 */
  const assetType = getSelectDataMapList(loadMapInfo?.[`${getTenantID()}${ILoadMapTypeAll.ASSET_TYPE}`], 'name', 'id', true);

  const [changeFromRef] = Form.useForm(); // 表单实例

  useEffect(() => {
    if (infoObj?.inventoryID) {
      const obj: any = {
        inventoryID: infoObj?.inventoryID,
        page: 1,
        rows: 10,
        changeState: '0,2,3',
        // isInventory: 0,
      };
      DetailPushRun(obj);
    }
  }, [infoObj?.inventoryID]);

  useEffect(() => {
    BasicMethods?.setFieldsValue({
      ...infoObj,
      rangeAssetClassID: infoObj?.rangeAssetClassID?.split(','),
      rangeDeptID: infoObj?.rangeDeptID?.split(','),
      rangeStartDate: infoObj?.rangeStartDate ? moment(infoObj?.rangeStartDate).format('YYYY-MM-DD') : '',
      rangeEndDate: infoObj?.rangeEndDate ? moment(infoObj?.rangeEndDate).format('YYYY-MM-DD') : '',
      createTime: moment(infoObj?.createTime).format('YYYY-MM-DD'),
    });
    ReMethods?.setFieldsValue({
      ...infoObj,
      rangeAssetClassID: infoObj?.rangeAssetClassID?.split(','),
      rangeDeptID: infoObj?.rangeDeptID?.split(','),
      rangeStartDate: infoObj?.rangeStartDate ? moment(infoObj?.rangeStartDate).format('YYYY-MM-DD') : '',
      rangeEndDate: infoObj?.rangeEndDate ? moment(infoObj?.rangeEndDate).format('YYYY-MM-DD') : '',
      createTime: moment(infoObj?.createTime).format('YYYY-MM-DD'),
    });
  }, [infoObj]);

  /** 表单配置项 */
  const fromConfig: any = useCallback(() => {
    return [
      {
        key: 'accept-basic',
        title: '',
        fieldChildren: [
          {
            field: `createTime`,
            label: `申请日期`,
            component: 'Input',
            disabled: true,
            placeholder: '自动带出',
          },
          {
            field: `applyCode`,
            label: `流水单号`,
            component: 'Input',
            disabled: true,
            placeholder: '自动带出',
          },
          {
            field: `createrName`,
            label: `盘点人`,
            component: 'Input',
            disabled: true,
            placeholder: '自动带出',
          },
          {
            field: `createPhone`,
            label: `联系电话`,
            component: 'Input',
            disabled: true,
            placeholder: '自动带出',
          },
          {
            field: `createDepartmentName`,
            label: `申请部门/单位`,
            component: 'Input',
            disabled: true,
            placeholder: '自动带出',
          },
          {
            field: `createPositionName`,
            label: `职务岗位`,
            component: 'Input',
            disabled: true,
            placeholder: '自动带出',
          },
        ],
      },
    ];
  }, [assetType, infoObj]);

  /** 表单配置项 */
  const fromConfigRe: any = useCallback(() => {
    return [
      // {
        // key: 'accept-basic',
        // title: '',
        // fieldChildren: [
          {
            field: `inventoryTitle`,
            label: `事项名称`,
            component: 'Input',
            disabled: true,
            placeholder: '自动带出',
            colSpan: 1,
          },
          {
            field: `rangeAssetClassID`,
            label: `资产类型范围`,
            component: 'Render',
            colSpan: 1,
            render: (text) => {
              return (
                <TreeSelect
                  placeholder="自动带出"
                  multiple
                  disabled
                  style={{
                    width: '100%',
                  }}
                  dropdownStyle={{
                    maxHeight: 400,
                    overflow: 'auto',
                  }}
                  fieldNames={{
                    label: 'name',
                    value: 'id',
                    children: 'children',
                  }}
                  treeData={addDisabledToTreeData(assetType)}
                  treeCheckable={true}
                  maxTagCount={3}
                />
              );
            },
          },
          {
            field: `rangeDeptID`,
            label: `部门范围`,
            component: 'Render',
            colSpan: 2,
            render: (text) => {
              return (
                <TreeSelect
                  placeholder="自动带出"
                  multiple
                  disabled
                  style={{
                    width: '100%',
                  }}
                  dropdownStyle={{
                    maxHeight: 400,
                    overflow: 'auto',
                  }}
                  fieldNames={{
                    label: 'text',
                    value: 'id',
                    children: 'children',
                  }}
                  treeData={getLevelZeroJson()}
                  treeCheckable={true}
                  maxTagCount={6}
                  showCheckedStrategy={TreeSelect.SHOW_PARENT}
                  treeDefaultExpandAll={true}
                />
              );
            },
          },

          {
            field: `rangeStartDate`,
            label: `取得开始时间`,
            component: 'Input',
            colSpan: 1,
            disabled: true,
            placeholder: '自动带出',
          },
          {
            field: `rangeEndDate`,
            label: `取得结束时间`,
            component: 'Input',
            colSpan: 1,
            disabled: true,
            placeholder: '自动带出',
          },
          {
            field: `billNum`,
            label: `账面总数`,
            component: 'Input',
            disabled: true,
            placeholder: '自动带出',
          },
          {
            field: `billSum`,
            label: `账面总额`,
            component: 'Input',
            placeholder: '自动带出',
            disabled: true,
          },
          {
            field: `inventoryNum`,
            label: `盘点总数`,
            component: 'Input',
            placeholder: '自动带出',
            disabled: true,
          },
          {
            field: `inventorySum`,
            label: `盘点总额`,
            component: 'Input',
            placeholder: '自动带出',
            disabled: true,
          },

          {
            field: `lossSum`,
            label: `盘亏汇总`,
            component: 'Input',
            placeholder: '自动带出',
            disabled: true,
          },
          {
            field: `surplusSum`,
            label: `盘盈汇总`,
            component: 'Input',
            placeholder: '自动带出',
            disabled: true,
          },
          {
            field: `inventoryInfo`,
            label: `盘点说明`,
            component: 'InputTextArea',
            placeholder: '自动带出',
            colSpan: 2,
            disabled: true,
          },
        // ],
      // },
      // {
      //   key: 'accept-procurement',
      //   title: '',
      //   fieldCustomDom: <>{<DifferTable inventoryID={infoObj?.inventoryID} isDetail={true} onSaveDiffFun={() => {}} />}</>,
      // },
    ];
  }, [assetType, infoObj]);

  // 表格表单配置信息
  const [config, BasicMethods] = useDescriptionsType({
    labelWidth: 200,
    basicForm: changeFromRef,
    schemas: fromConfig(),
  });
  // 表格表单配置信息
  const [ReConfig, ReMethods] = useDescriptions({
    labelWidth: 200,
    basicForm: changeFromRef,
    schemas: fromConfigRe(),
  });

  return (
    <>
      <div className="commonTabsBodyDom">
        <div className={Cls('tabsBodyInfoDom', `${styleFixCls}updateFormBox`)}>
          <ScrollBarLayout style={{ padding: '20px 10%' }}>
            <Spin spinning={mapLoading}>
              <TypographyTitle children={'盘点汇报申请'} style={{ textAlign: 'center', borderLeft: 'none' }} level={1} />
              <TypographyTitle children={'基本信息'} style={{ margin: '25px 0px 20px' }} level={2} />
              <DescriptionsType config={config} />

              <TypographyTitle children={'盘点汇报信息'} style={{ margin: '25px 0px 20px' }} level={2} />
              <Descriptions config={ReConfig} />

              <TypographyTitle children={'资产详单'} style={{ margin: '25px 0px 20px' }} level={2} />
              <DifferTable inventoryID={infoObj?.inventoryID} isDetail={true} onSaveDiffFun={() => {}} detailInfo={infoObj} Detaildata={Detaildata} taskPushPagination={taskPushPagination} taskPushLoading={taskPushLoading} editDetailRun={editDetailRun} editDetailLoading={editDetailLoading} />
            </Spin>
          </ScrollBarLayout>
        </div>
      </div>
    </>
  );
};

export default connect(({ baseLogin, navTab }: Record<string, any>) => ({
  curRes: baseLogin?.permissions,
  navTab,
}))(DetailInfoCenterViewMainOA);
